const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:'); // 使用内存数据库，方便开发和测试

// 创建表
db.serialize(() => {
  db.run(`
    CREATE TABLE IF NOT EXISTS sensor_data (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      zd_id INTEGER,
      datetime TEXT,
      temperature REAL,
      comgas REAL,
      flame REAL,
      shake REAL,
      light REAL
    )
  `);
});

// 保存数据
function saveData(data) {
  const stmt = db.prepare(`
    INSERT INTO sensor_data (zd_id, datetime, temperature, comgas ,flame ,shake ,light) 
    VALUES (?, ?, ?, ?, ?, ?, ?)
  `);
  stmt.run(data.zd_id, data.datetime , data.temperature, data.comgas , data.flame , data.shake , data.light);
  stmt.finalize();
}

// 获取历史数据
function getHistory(callback) {
  db.all('SELECT * FROM sensor_data ORDER BY datetime DESC', (err, rows) => {
    if (err) {
      console.error(err);
      callback([]);
    } else {
      callback(rows);
    }
  });
}

module.exports = {
  saveData,
  getHistory
};
